﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace DaZhong.app_code
{
    public static class AliApiNewsFetch
    {
        private const string host = "http://jisunews.market.alicloudapi.com";
        private const string path = "/news/get";
        private const string method = "GET";
        private const string appcode = "871d28397971483e943b7e11bf2e5103";
        private const string querys1= "channel=%E5%A4%B4%E6%9D%A1&num=10&start=0";
        private const string querys2= "channel=%E6%96%B0%E9%97%BB&num=10&start=0";

        public static IList<MArticle> GetArticles()
        {
            var result = new List<MArticle>();
            if (!Debugger.IsAttached)
            {
                if (DateTime.Now.Hour != 9 || DateTime.Now.Hour != 14) return result;
            }
            
            var toutiaoJsonString = GetJsonString(querys1);
            var newJsonString = GetJsonString(querys2);
            var ttNews = JsonConvert.DeserializeObject<NewsRoot>(toutiaoJsonString);
            var news = JsonConvert.DeserializeObject<NewsRoot>(newJsonString);
            var result1= ttNews.result.list.Select(ttNew => new MArticle()
            {
                sourceid = (int) EnumTypes.SourceIds.AliApiTouTiao,
                source = ttNew.src, date = DateTime.Now.ToString(),
                title = ttNew.title,
                logo = ttNew.pic,
                htmlurl = ttNew.weburl,
                state = 0,
                content = GetImgP(ttNew.pic) + ttNew.content,
                html_date = ttNew.time
            }).ToList();
            result.AddRange(result1);
            //var result2 = news.result.list.Select(n => new MArticle()
            //{
            //    sourceid = (int)EnumTypes.SourceIds.AliApiTouTiao,
            //    source = n.src,
            //    date = DateTime.Now.ToString(),
            //    title = n.title,
            //    logo = n.pic,
            //    htmlurl = n.weburl,
            //    state = 0,
            //    content = GetImgP(n.pic)+n.content,
            //    html_date = n.time
            //}).ToList();
            //result.AddRange(result2);
            return result;
        }

        private static string GetJsonString(string querys)
        {
            
            var bodys = "";
            var url = host + path;
            HttpWebRequest httpRequest = null;
            HttpWebResponse httpResponse = null;

            if (0 < querys.Length)
            {
                url = url + "?" + querys;
            }

            if (host.Contains("https://"))
            {
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                httpRequest = (HttpWebRequest)WebRequest.CreateDefault(new Uri(url));
            }
            else
            {
                httpRequest = (HttpWebRequest)WebRequest.Create(url);
            }
            httpRequest.Method = method;
            httpRequest.Headers.Add("Authorization", "APPCODE " + appcode);
            if (0 < bodys.Length)
            {
                var data = Encoding.UTF8.GetBytes(bodys);
                using (var stream = httpRequest.GetRequestStream())
                {
                    stream.Write(data, 0, data.Length);
                }
            }
            try
            {
                httpResponse = (HttpWebResponse)httpRequest.GetResponse();
            }
            catch (WebException ex)
            {
                httpResponse = (HttpWebResponse)ex.Response;
            }
            var st = httpResponse.GetResponseStream();
            using (var reader = new StreamReader(st, Encoding.GetEncoding("utf-8")))
            {
                var jsonString = reader.ReadToEnd();
                return jsonString;
            }
        }

        private static string GetImgP(string url)
        {
            return $"<p><img style = \"-webkit-user-select: none\" src = \"{url}\" /></p>";
        }


        public static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {
            return true;
        }
    }
    public class NewsRoot
    {
        /// <summary>
        /// 
        /// </summary>
        public string status { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string msg { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public NewsResult result { get; set; }
    }
    public class NewsResult
    {
        /// <summary>
        /// 头条
        /// </summary>
        public string channel { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string num { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public List<NewsListItem> list { get; set; }
    }
    public class NewsListItem
    {
        /// <summary>
        /// 诺基亚6预约量或突破百万
        /// </summary>
        public string title { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string time { get; set; }
        /// <summary>
        /// 手机中国
        /// </summary>
        public string src { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string category { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string pic { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string content { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string url { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string weburl { get; set; }
    }
}
